package net.spatula.tally_ho.ui.signin;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import net.spatula.tally_ho.jpa.ResourceManager;
import net.spatula.tally_ho.service.UserService;
import net.spatula.tally_ho.service.beans.UserBean;
import wicket.PageParameters;
import wicket.markup.html.WebPage;
import wicket.markup.html.form.Form;
import wicket.markup.html.form.PasswordTextField;
import wicket.markup.html.form.TextField;
import wicket.markup.html.panel.FeedbackPanel;
import wicket.model.PropertyModel;
import wicket.protocol.http.WebRequestCycle;
import wicket.protocol.http.WebResponse;
import wicket.util.value.ValueMap;

/**
 * @author spatula
 * 
 */
public final class SignIn extends WebPage {

    private static final long serialVersionUID = 1L;
    private String returnTo = null;

    public SignIn() {
        this((PageParameters) null);
    }

    /**
     * Constructor
     * 
     * @param parameters
     *            The page parameters
     */
    public SignIn(final PageParameters parameters) {
        // Create feedback panel and add to page
        final FeedbackPanel feedback = new FeedbackPanel("feedback");

        add(feedback);

        // Add sign-in form to page, passing feedback panel as validation error
        // handler
        add(new SignInForm("signInForm"));
    }

    public SignIn(String returnTo) {
        this();
        this.returnTo = returnTo;

    }

    /**
     * Sign in form
     * 
     * @author Jonathan Locke
     */
    public final class SignInForm extends Form {

        private static final long serialVersionUID = 1L;
        // El-cheapo model for form
        private final ValueMap properties = new ValueMap();

        /**
         * Constructor
         * 
         * @param id
         *            id of the form component
         */
        public SignInForm(final String id) {
            super(id);

            // Attach textfield components that edit properties map model
            add(new TextField("username", new PropertyModel(properties, "username")));
            add(new PasswordTextField("password", new PropertyModel(properties, "password")));
        }

        /**
         * @see wicket.markup.html.form.Form#onSubmit()
         */
        public final void onSubmit() {

            EntityManagerFactory emf = ResourceManager.getInstance().getEMF();
            EntityManager em = emf.createEntityManager();

            UserBean userFromDatabase = UserService.getInstance().authenticateUser(em, properties.getString("username"),
                    properties.getString("password"));

            // Sign the user in
            if (userFromDatabase != null && userFromDatabase.isAuthenticated()) {
                Utils.setUserBean(userFromDatabase);
                if (!continueToOriginalDestination()) {
                    if (returnTo != null) {
                        ((WebResponse) (WebRequestCycle.get().getResponse())).redirect(returnTo);
                    } else {
                        setResponsePage(WebRequestCycle.get().getApplication().getHomePage());
                    }
                }
            } else {
                // Form method that will notify feedback panel
                // Try the component based localizer first. If not found try the
                // application localizer. Else use the default
                final String errmsg = getLocalizer().getString("loginError", this, "Unable to sign you in");
                error(errmsg);
            }
        }
    }
}